import { login, logout, getInfo, Validate, userlogin } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import userdate from '@/utils/user.js';
const defAva = '';
const userDateInfo = '';

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo) {
      return new Promise((resolve, reject) => {
        userlogin({ ...userInfo })
          .then((res) => {
            if (res.code === 200 || res.code === 20000) {
              // 保存token的数据
              localStorage.setItem('userDateInfo', JSON.stringify(res.data));
              setToken(res.data.token);
              this.token = res.data.token;
              resolve(userDateInfo);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        const res = userdate;
        const user = res.user;
        const avatar =
          user.avatar == '' || user.avatar == null
            ? defAva
            : import.meta.env.VITE_APP_BASE_API + user.avatar;

        if (res.roles && res.roles.length > 0) {
          // 验证返回的roles是否是一个非空数组
          this.roles = res.roles;
          this.permissions = res.permissions;
        } else {
          this.roles = ['ROLE_DEFAULT'];
        }
        this.id = user.userId;
        this.name = user.userName;
        this.avatar = avatar;
        resolve(res);
      }).catch((error) => {
        reject(error);
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        this.token = '';
        this.roles = [];
        this.permissions = [];
        removeToken();
        resolve();
      });
    },
  },
});

export default useUserStore;
